<template>
  <div class="device">
    <div class="header">
      <div class="mask">设备详情</div>
    </div>
    <div class="main">
      <div v-if="sensorData.length > 0" style="display: flex; flex-wrap: wrap; ">
        <div v-for="sensor in sensorData" :key="sensor.sensor_id" class="sensor-container">
          <h2>传感器 ID: {{ sensor.sensor_id }}</h2>
          <p><strong>设备 ID:</strong> {{ sensor.device_id }}</p>
          <p><strong>传感器类型:</strong> {{ sensor.sensor_type }}</p>
          <p><strong>数据采集时间:</strong> {{ formatDate(sensor.data_collection_time) }}</p>
          <p><strong>运动状态:</strong> {{ sensor.motion_status }}</p>
          <p><strong>烟雾检测:</strong> {{ sensor.smoke_detected ? '检测到' : '未检测到' }}</p>
          <p><strong>创建时间:</strong> {{ formatDate(sensor.created_at) }}</p>

          <div >
			<div :id="'containertureChart' + sensor.sensor_id" class="chart-container"></div>
			  
			<div :id="'temperatureChart' + sensor.sensor_id" class="chart-container"></div>
			  
			<div :id="'humidityChart' + sensor.sensor_id" class="chart-container"></div>
			  
		  </div>
			
		  
          
        </div>
      </div>
      <div v-else>
        <p>没有可用的传感器数据。</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  setup() {
    const sensorData = ref([]);
    const errorMessage = ref('');
    const instance = getCurrentInstance();

    onMounted(async () => {
      const deviceId = parseInt(getDeviceId(), 10);
      if (deviceId) {
        try {
          const token = localStorage.getItem('token');
          const url = `/user/sensors/${deviceId}`;
          const response = await axios.get(url, {
            headers: {
              'Authorization': `Bearer ${token}`,
            },
          });

          if (response.data.code === 100) {
            sensorData.value = response.data.data || [];
            await nextTick(); // Wait for DOM updates
            updateCharts(); // Update charts
          } else {
            errorMessage.value = response.data.message || '获取传感器数据失败';
            redirectToHome();
          }
        } catch (error) {
          errorMessage.value = '发生错误，请检查网络连接。';
        }
      } else {
        errorMessage.value = '设备 ID 无效';
      }
    });

    function getDeviceId() {
      return instance?.proxy.$route.params.deviceId;
    }

    function redirectToHome() {
      window.location.href = '/index';
    }

    function formatDate(timestamp) {
      const date = new Date(timestamp);
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      };
      return date.toLocaleString('zh-CN', options);
    }

    function updateCharts() {
      sensorData.value.forEach((sensor) => {
        const containerChartDom = document.getElementById('containertureChart' + sensor.sensor_id);
        const tempChartDom = document.getElementById('temperatureChart' + sensor.sensor_id);
        const humidChartDom = document.getElementById('humidityChart' + sensor.sensor_id);

        // Create charts for temperature, light intensity, and humidity
        createChart(tempChartDom, '温度仪表盘', sensor.temperature, 100, '°C');
        createChart(containerChartDom, '光强仪表盘', sensor.light_intensity, 100, 'lx');
        createChart(humidChartDom, '湿度仪表盘', sensor.humidity, 100, '%');
      });
    }

    function createChart(dom, title, value, max, unit) {
      if (value > 0 && dom) {
        // Clear previous chart instance
        if (dom.__echarts__) echarts.dispose(dom);

        // Initialize ECharts
        const chart = echarts.init(dom);
        chart.setOption({
          title: {
            text: title,
            left: 'center',
            top: '10%',
          },
          series: [{
            type: 'gauge',
            min: 0,
            max: max,
            radius: '70%',
            axisLine: {
              lineStyle: {
                width: 10,
                color: [[0.2, '#ff4500'], [0.8, '#ffa500'], [1, '#ff0000']],
              },
            },
            splitLine: {
              length: 20,
              lineStyle: {
                width: 2,
                color: '#eee',
              },
            },
            pointer: {
              width: 5,
            },
            detail: {
              formatter: `{value} ${unit}`,
              offsetCenter: [0, '50%'],
            },
            data: [{ value: value, name: title }],
          }],
        });
      } else if (dom) {
        // Hide chart if value is zero
        dom.style.display = 'none';
      }
    }

    return {
      sensorData,
      errorMessage,
      formatDate,
    };
  },
};
</script>

<style scoped>
.device {
  height: 100vh;
  width: 100vw;
  background-color: #e0f7fa;
  display: flex;
  flex-direction: column;
}

.device > .header {
  height: 150px;
  background-color: #80deea;
  position: relative;
}

.device > .header > .mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  font-size: 3em;
  text-align: center;
  z-index: 1;
}

.main {
  width: 80%;
  flex-grow: 1;
  padding: 20px; /* Updated padding for better spacing */
  overflow-y: auto;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.sensor-container {
  
  width: 420px;
  margin: 15px; /* Added margin for spacing between sensors */
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  background-color: #dcfbff; /* Optional: add a background color to sensor containers */
}

h2 {
  font-size: 2vw;
  margin: 0; /* Remove default margin */
}

strong {
  font-size: 1vw;
  color: #00796b;
}

p {
  font-size: 1vw;
  margin: 5px 0;
  line-height: 1.5;
}

.chart-container {
  display: inline-block;
  width: 400px;
  height: 400px;
}

@media (max-width: 768px) {
  .sensor-container {
    width: 90vw;
  }

  .device > .header > .mask {
    font-size: 5vw;
  }
}
</style>
